import React from "react";
import PropTypes from 'prop-types';
import Snackbar from "@material-ui/core/es/Snackbar/Snackbar";
import bindthis from 'autobind-decorator'
import {injectReducer} from "../store/reducers";
import {store} from "../main"


@bindthis
export default class Toast extends React.Component {

	static ACTION_NAME = "TOAST";
	static contextTypes = {store: PropTypes.object.isRequired}

	state = {open: false, text: ":)"}

	static show(text) {
		store.dispatch({type: Toast.ACTION_NAME, text: text})
	}

	constructor(props, context) {
		super(props, context)

		const {store} = context;
		console.log("injected")

		let timerId = null;

		const reducer = (state = "", action) => {
			if (action.type !== Toast.ACTION_NAME)
				return state;

			if (timerId)
				clearTimeout(timerId)

			if (!action.text || action.text.length === 0) {
				this.setState({open: false})
			} else {
				this.setState({open: true, text: action.text})
				timerId = setTimeout(() => store.dispatch({type: Toast.ACTION_NAME, text: null}), 1000)
			}

			return action.text
		}

		injectReducer(store, {key: Toast.ACTION_NAME, reducer})
	}

	render() {
		return (
			<Snackbar anchorOrigin={{vertical: "top", horizontal: "center"}}
			          open={this.state.open}
			          ContentProps={{'aria-describedby': 'message-id'}}
			          message={
				          <span id="message-id">{this.state.text}</span>
			          }
			/>
		)
	}
}

